package com.wcy.aspect;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSON;
import com.wcy.model.WebLog;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.annotation.Order;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.HashMap;

/**
 * <p>Title:WebLogAspect.java</p >
 * <p>Description: </p >
 * <p>Copyright: 公共服务与应急管理战略业务本部 Copyright(c)2020</p >
 * <p>Date:2021/9/16 15:50</p >
 *
 * @author wcy (wangchaoyanga@mail.taiji.com.cn)
 * @version 1.0
 */
@Component
@Aspect
@Order(1)
@Slf4j
public class WebLogAspect {

    /**
     * 日志记录:
     *      环绕通知
     */

    /**
     * 1.定义切入点
     */
    @Pointcut("execution(* com.wcy.controller.*.*(..))")
    public void webLog(){

    }

    /**
     * 2.记录日志的环绕通知
     */
    @Around("webLog()")
    public Object recordWebLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object result = null;
        WebLog webLog=new WebLog();
        long start = System.currentTimeMillis();

        // 执行真实方法
        result = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());

        long end = System.currentTimeMillis();

        webLog.setSpendTime((int) ((end-start)/1000));

        // 获取当前请求的request对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        // 获取安全上下文
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        String url=request.getRequestURL().toString();
        webLog.setUri(request.getRequestURI());
        webLog.setUrl(url);
        webLog.setBasePath(StrUtil.removeSuffix(url, URLUtil.url(url).getPath())); // http://ip:port
        webLog.setUsername(authentication == null ? "anonymous" : authentication.getName());
        webLog.setIp(request.getRemoteAddr()); // TODO

        // 获取方法
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        // 获取类的名称
        String targetClassName = proceedingJoinPoint.getTarget().getClass().getName();
        Method method = signature.getMethod();
        // 因为我们使用了swagger 我们必须在方法上面添加 @ApiOperation(value="")注解
        ApiOperation annotation = method.getAnnotation(ApiOperation.class);
        webLog.setDescription(annotation == null ? "no desc" : annotation.value());
        webLog.setMethod(targetClassName+"."+method.getName());
        webLog.setParameter(getMethodParameter(method,proceedingJoinPoint.getArgs())); // {key:value}
        webLog.setResult(result);
        log.info(JSON.toJSONString(webLog,true));
        return result;
    }

    /**
     * 获取方法的执行参数
     * @param method
     * @param args
     * @return
     */
    private Object getMethodParameter(Method method, Object[] args) {
        HashMap<String, Object> methodParametersWithValues = new HashMap<>();
        LocalVariableTableParameterNameDiscoverer localVariableTableParameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer();
        // 方法的形参名称
        String[] parameterNames = localVariableTableParameterNameDiscoverer.getParameterNames(method);
        for(int i =0 ;i < parameterNames.length ; i++){
            if(parameterNames[i].equals("password")||parameterNames[i].equals("file")){
                methodParametersWithValues.put(parameterNames[i],"受限的支持类型");
            }else {
                methodParametersWithValues.put(parameterNames[i],args[i]);
            }
        }
        return methodParametersWithValues;
    }
}
